What is xhr?
The xhr npm package is a simple and lightweight library for making XMLHttpRequests in a browser environment. It provides a straightforward API for performing HTTP requests, handling responses, and managing errors.
What are xhr's main functionalities?
Basic GET Request
This feature allows you to perform a basic GET request to a specified URL. The callback function handles the response or any errors that occur.
const xhr = require('xhr');
xhr({ url: 'https://api.example.com/data' }, function (err, resp, body) {
if (err) {
console.error(err);
} else {
console.log(body);
}
});
POST Request with Data
This feature allows you to perform a POST request with a JSON payload. The request includes headers to specify the content type, and the callback function handles the response or any errors.
const xhr = require('xhr');
xhr({
url: 'https://api.example.com/data',
method: 'POST',
body: JSON.stringify({ key: 'value' }),
headers: { 'Content-Type': 'application/json' }
}, function (err, resp, body) {
if (err) {
console.error(err);
} else {
console.log(body);
}
});
Handling Response Status Codes
This feature demonstrates how to handle different HTTP response status codes. The callback function checks the status code and logs the appropriate message.
const xhr = require('xhr');
xhr({ url: 'https://api.example.com/data' }, function (err, resp, body) {
if (err) {
console.error(err);
} else if (resp.statusCode === 200) {
console.log('Success:', body);
} else {
console.log('Error:', resp.statusCode);
}
});
Other packages similar to xhr
axios
Axios is a promise-based HTTP client for the browser and Node.js. It provides a more powerful and flexible API compared to xhr, including support for interceptors, automatic JSON transformation, and request cancellation.
fetch
Fetch is a built-in web API for making HTTP requests in the browser. It is a modern alternative to XMLHttpRequest and provides a more powerful and flexible API. Unlike xhr, fetch is built into modern browsers and does not require an external library.
superagent
Superagent is a small, progressive client-side HTTP request library. It provides a more feature-rich API compared to xhr, including support for promises, request retries, and plugins.
xhr
A small xhr wrapper. Designed for use with browserify.
Example
var xhr = require("xhr")
xhr({
body: someJSONString,
uri: "/foo",
headers: {
"Content-Type": "application/json"
}
}, function (err, resp, body) {
})
var req = xhr(options, callback)
type XhrOptions = String | {
useXDR: Boolean?,
sync: Boolean?,
uri: String,
url: String,
method: String?,
timeout: Number?,
headers: Object?,
body: String?,
json: Object?,
withCredentials: Boolean?,
response: Boolean?
}
xhr := (XhrOptions, Callback<Response>) => Request
the returned object is either an XMLHttpRequest
instance
or an XDomainRequest
instance (if on IE8/IE9 &&
options.useXDR
is set to true
)
Your callback will be called once with the arguments
( Error
, response
, body
) where the response is depending on
options.response
and body will be either
xhr.response
, xhr.responseText
or
xhr.responseXML
depending on the request type.
Your callback will be called with an Error
if the
resulting status of the request is either 0
, 4xx
or 5xx
If options
is a string then it's a short hand for
{ method: "GET", uri: string }
options.method
Specify the method the XMLHttpRequest
should be opened
with. Passed to xhr.open
. Defaults to "GET"
options.response
Specify the format of the response. Defaults to return the xhr/xdr-object
with body, headers and status-properties added. When set to true
a special response
object is returned that includes parsed response headers, status and body.
options.response
must be set to true
for IE8 support.
options.useXDR
Specify whether this is a cross origin (CORS) request for IE<10.
Switches IE to use XDomainRequest
instead of XMLHttpRequest
.
Ignored in other browsers.
Note that headers cannot be set on an XDomainRequest instance.
options.sync
Specify whether this is a synchrounous request. Note that when
this is true the callback will be called synchronously. In
most cases this option should not be used. Only use if you
know what you are doing!
options.body
Pass in body to be send across the XMLHttpRequest
.
Generally should be a string. But anything that's valid as
a parameter to xhr.send
should work
options.uri
or options.url
The uri to send a request too. Passed to xhr.open
. options.url
and options.uri
are aliases for each other.
An object of headers that should be set on the request. The
key, value pair is passed to xhr.setRequestHeader
options.timeout
A numeric timeout to use for this xhr request. Defaults to 5
seconds. Ignored when options.sync
is true.
options.json
A valid JSON serializable value to be send to the server. If this
is set then we serialize the value and use that as the body.
We also set the Content-Type to "application/json"
.
Additionally the response body is parsed as JSON
options.withCredentials
Specify whether user credentials are to be included in a cross-origin
request. Sets xhr.withCredentials
. Defaults to false.
For backward-compatibility defaults to true
when deprecated options.cors
is also true.
A wildcard *
cannot be used in the Access-Control-Allow-Origin
header when withCredentials
is true.
The header needs to specify your origin explicitly or browser will abort the request.
MIT Licenced